package com.lingxu.module.collaborative.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.lingxu.base.common.api.vo.Result;
import com.lingxu.base.common.exception.BussException;
import com.lingxu.base.common.util.DateUtil;
import com.lingxu.base.system.fileManage.entity.SysFileInfo;
import com.lingxu.base.system.manage.vo.LoginUser;
import com.lingxu.module.collaborative.entity.Collaborative;
import com.lingxu.module.collaborative.service.CollaborativeService;
import dm.jdbc.filter.stat.json.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
* @Description: 协同编辑
* @Author: 金飞翔
*/
@Slf4j
@Api(tags="协同编辑")
@RestController
@RequestMapping("/collaborative")
public class CollaborativeController {
   @Value(value = "${uploadUrl}")
   private String uploadpath;

   @Value(value = "${collaborativeUrl}")
   private String collaborativeUrl;
   @Value(value = "${collaborativeCUrl}")
   private String collaborativeCUrl;

   @Resource
   private CollaborativeService collaborativeService;

   @ApiOperation(value="协同新增", notes="文件上传-并保存入库")
   @PostMapping(value = "/collaborativeUpload")
   public Result upload(HttpServletRequest request, HttpServletResponse response){
      Result<SysFileInfo> result = new Result<>();
      LoginUser userNow = SecurityUtils.getSubject().getPrincipal() != null ? (LoginUser) SecurityUtils.getSubject().getPrincipal() : null;
      String resuceMatters = request.getParameter("resuceMatters");
      String modelRequire = request.getParameter("modelRequire");
      String createIdcard = request.getParameter("createIdcard");
      String createName = request.getParameter("createName");
      String doMain = request.getParameter("doMain");

      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
//		 上传至本地服务器
      String savePath = this.uploadLocal(file);
      if(StringUtils.isEmpty(savePath)){
         result.setMessage("上传失败！");
         result.setSuccess(false);
         return result;
      }
      String fileNameS = "";
      try {

         result.setMessage("上传成功！");
         result.setSuccess(true);

         //调取协同接口
         int userId = Integer.parseInt(userNow.getRemark());
         String filenamef = "";
         try {
            // 1. 创建URL对象
            URL url = new URL(collaborativeUrl);

            // 2. 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 3. 设置连接属性
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + "----boundary");

            // 4. 创建文件输入流
            File fileXt = new File(savePath);
            filenamef = fileXt.getName();
            FileInputStream fileInputStream = new FileInputStream(fileXt);

            // 5. 获取输出流并写入表单数据
            OutputStream outputStream = connection.getOutputStream();
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8), true);
            String boundary = "----boundary";

            // 写入参数
            writer.append("--").append(boundary).append("\r\n");
            writer.append("Content-Disposition: form-data; name=\"userId\"\r\n\r\n");
            writer.append(String.valueOf(userId)).append("\r\n");
            writer.flush();


            // 写入文件表单字段
            writer.append("--").append(boundary).append("\r\n");
            writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileXt.getName() + "\"\r\n");
            writer.append("Content-Type: application/octet-stream\r\n\r\n");
            writer.flush();

            // 写入文件内容
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
               outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();

            // 写入表单结束标志
            writer.append("\r\n").append("--").append(boundary).append("--\r\n");
            writer.close();

            // 6. 关闭流
            fileInputStream.close();
            outputStream.close();

            // 7. 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("响应码: " + responseCode);

            // 8. 处理响应
            if (responseCode == HttpURLConnection.HTTP_OK) {
               // 读取响应内容
               BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
               String inputLine;
               StringBuilder responseXt = new StringBuilder();
               while ((inputLine = in.readLine()) != null) {
                  responseXt.append(inputLine);
               }
               in.close();
               // 打印响应内容
               System.out.println("响应内容: " + responseXt.toString());
               // 解析JSON响应内容
               JSONObject jsonResponse = new JSONObject(responseXt.toString());
               String filename = jsonResponse.getString("filename");
               System.out.println("文件名: " + filename);
               // 9. 断开连接
               connection.disconnect();
               //第一次访问converter
               int step = 0;
               int count = 1 ;
               Map<String,Object> pm = new HashMap<>();
               while (step == 0) {

                  pm.put("filename",filename);
                  pm.put("filePass",null);
                  String post = HttpUtil.post(collaborativeCUrl+"?userId="+userId, JSON.toJSONString(pm));

                  System.out.println(post);
                  com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(post);
                  if (null != jsonObject.getString("documentType") && jsonObject.getString("documentType").length()>0){
                     fileNameS = jsonObject.getString("filename");
                     break;
                  }
                  step=jsonObject.getInteger("step");
                  pm.put("filename",jsonObject.getString("filename"));
                  Thread.sleep(500);
               }
            } else {
               System.out.println("请求失败");
            }

         } catch (IOException e) {
            e.printStackTrace();
         }

         //数据入库
         Collaborative collaborative = new Collaborative();
         collaborative.setId(UUID.randomUUID().toString());
         collaborative.setModelName("");
         collaborative.setCreateName(createName);
         collaborative.setCreateIdcard(createIdcard);
         collaborative.setFileNamef(filenamef);
         collaborative.setFilePathf(savePath);
         collaborative.setFileNames(fileNameS);
         collaborative.setModelRequire(modelRequire);
         collaborative.setResuceMatters(resuceMatters);
         collaborative.setAskName(userNow.getUsername());
         collaborative.setAskTime(DateUtil.getDateRandom());
         collaborative.setReviewStatus("0");
         collaborative.setUploadTime(DateUtil.getDateRandom());
         collaborative.setDoMain(doMain);
         collaborativeService.insertCollaborative(collaborative);
      } catch (Exception e) {
         result.setMessage("上传文件错误！"+ e.getMessage());
         result.setSuccess(false);
         throw new BussException("上传文件错误！"+ e.getMessage());
      }
      return result;
   }

   /**
    * 本地文件上传
    * @param mf 文件
    * @return
    */
   private String uploadLocal(MultipartFile mf){
      try {
         String ctxPath = uploadpath + "/infos/";
         String fileName = null;
         File file = new File(ctxPath);
         if (!file.exists()) {
            file.mkdirs();// 创建文件根目录
         }
         String orgName = mf.getOriginalFilename();// 获取文件名
         if(orgName.lastIndexOf(".")<0){
            fileName=orgName+ "_" + System.currentTimeMillis();
         }else{
            fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
         }
         String savePath = ctxPath + fileName;
         File savefile = new File(savePath);
         FileCopyUtils.copy(mf.getBytes(), savefile);
         return ctxPath + fileName;
      } catch (IOException e) {
         log.error(e.getMessage(), e);
      }
      return "";
   }

   /**
    * @Author
    * @Description 协同列表查询
    * @Date 2024/4/10 19:27
    * @Param
    * @return
    **/
   @ApiOperation(value="协同列表查询")
   @PostMapping(value = "/findcollaborativeList")
   public Result findcollaborativeList(@RequestBody Collaborative params) {
      return collaborativeService.findCollaborativeList(params);
   }

   /**
    * @Author
    * @Description 协同删除
    * @Date 2024/4/10 19:28
    * @Param
    * @return
    **/
   @ApiOperation(value="协同删除")
   @PostMapping(value = "/deleteCollaborativeById")
   public Result deleteCollaborativeById(String id) {
      return  collaborativeService.deleteCollaborativeById(id);
   }

   /**
    * @Author 
    * @Description 审核
    * @Date 2024/4/10 19:34
    * @Param 
    * @return 
    **/
   @ApiOperation(value="协同审批")
   @PostMapping(value = "/auditingById")
   public Result auditingById(String id,String reviewStatus) {
      Collaborative collaborative = new Collaborative();
      collaborative.setId(id);
      collaborative.setReviewStatus(reviewStatus);
      return  collaborativeService.auditingById(collaborative);
   }

   @ApiOperation(value="协同修改")
   @PostMapping(value = "/updateById")
   public boolean updateById(String id, String resuceMatters, String modelRequire) {
      Collaborative collaborative = new Collaborative();
      collaborative.setId(id);
      collaborative.setResuceMatters(resuceMatters);
      collaborative.setModelRequire(modelRequire);
      return  collaborativeService.updateById(collaborative);
   }
}
